package com.example.kt_fast.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.RecyclerView
import com.example.kt_common.util.AppCommonUitl.context
import com.example.kt_common.util.ToastUtil
import com.example.kt_fast.R
import com.example.kt_fast.bean.TreeNode

/**
 * Created by 小陈 on 2025/3/31.
 * Time: 22:46.
 */
class CarTreeAdapter(private val allNodes: List<TreeNode>) :
    RecyclerView.Adapter<CarTreeAdapter.ViewHolder>() {

    private val visibleNodes = mutableListOf<TreeNode>()

    init {
        buildVisibleNodes(allNodes)
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val ivArrow: ImageView = itemView.findViewById(R.id.ivArrow)
        val tvIcon: TextView = itemView.findViewById(R.id.tvIcon)
        val tvName: TextView = itemView.findViewById(R.id.tvName)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.item_tree_node, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val node = visibleNodes[position]

        // 设置左边距缩进
        val params = holder.itemView.layoutParams as RecyclerView.LayoutParams
        params.marginStart = node.level * 30.dpToPx(holder.itemView.context)
        holder.itemView.layoutParams = params

        holder.tvName.text = node.name
//        // 加载字体
//        val typeface = ResourcesCompat.getFont(context!!, R.font.iconfont)
//        // 设置图标
//        holder. tvIcon.typeface = typeface
        holder. tvIcon.text =  context!!.resources.getString(R.string.ic_folder) // 例如：FontAwesome 的 "home" 图标

        holder.ivArrow.rotation = if (node.isExpanded) 90f else 0f
        holder.ivArrow.visibility = if (node.children.isEmpty()) View.INVISIBLE else View.VISIBLE

        holder.itemView.setOnClickListener {
            if (node.children.isEmpty()) {
                ToastUtil.showMsg(node.name)
                return@setOnClickListener
            }
            node.isExpanded = !node.isExpanded
            updateVisibleNodes()
        }
    }

    override fun getItemCount() = visibleNodes.size

    private fun buildVisibleNodes(nodes: List<TreeNode>) {
        nodes.forEach { node ->
            visibleNodes.add(node)
            if (node.isExpanded) {
                buildVisibleNodes(node.children)
            }
        }
    }

    private fun updateVisibleNodes() {
        visibleNodes.clear()
        buildVisibleNodes(allNodes)
        notifyDataSetChanged()
    }

    private fun Int.dpToPx(context: Context): Int =
        (this * context.resources.displayMetrics.density).toInt()
}
